package net.ufrog.common;

import net.ufrog.common.app.App;
import net.ufrog.common.utils.Strings;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * 消息
 * 
 * @author ultrafrog
 * @version 1.0, 2012-11-30
 * @since 1.0
 */
public class Messages {

    private static final String CONF_BASENAME = App.config("app.i18n.basename", "messages");

    /** 构造函数 */
    private Messages() {}

    /**
     * 读取资源包
     *
     * @param locale 区域
     * @return 资源包
     */
    public static ResourceBundle getBundle(Locale locale) {
        if (locale == null) locale = Locale.getDefault();
        return ResourceBundle.getBundle(CONF_BASENAME, locale);
    }

    /**
     * 读取资源包
     *
     * @param locale 区域字符串
     * @return 资源包
     */
    public static ResourceBundle getBundle(String locale) {
        return getBundle(parseLocaleString(locale));
    }

    /**
     * 读取资源
     *
     * @param locale 区域
     * @param key 键值
     * @return 消息字符串
     */
    public static String get(Locale locale, String key) {
        try {
            return getBundle(locale).getString(key);
        } catch (MissingResourceException e) {
            Logger.warn(e.getMessage());
            return key;
        }
    }

    /**
     * 读取资源
     *
     * @param locale 区域
     * @param key 键值
     * @param args 参数数组
     * @return 消息字符串
     */
    public static String get(Locale locale, String key, Object... args) {
        return String.format(get(locale, key), args);
    }

    /**
     * 解析位置字符串
     *
     * @param locale 区域字符串
     * @return 区域对象
     */
    public static Locale parseLocaleString(String locale) {
        String parts[] = locale.split("_");
        String language = (parts.length > 0) ? parts[0] : "";
        String country = (parts.length > 1) ? parts[1] : "";
        return !Strings.empty(language) ? new Locale(language, country) : null;
    }
}
